package com.binarysoft.cmdhandler.user;

import java.util.Collection;
import java.util.StringTokenizer;

import com.binarysoft.service.user.UserInfo;
import com.binarysoft.service.user.UserService;

import common.framework.command.handler.AbstractCommandHandler;
import common.framework.command.helper.CommandHelper;
import common.framework.command.server.Terminal;
import common.framework.dsb.annotation.DSBCmd;
import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;

@DSBCmd("user")
public class UserCmdHandler extends AbstractCommandHandler {

	@Override
	public void handle(String args, Terminal terminal) throws Exception {
		terminal.println("");
		StringTokenizer stier = new StringTokenizer(args);
		int count = stier.countTokens();
		if (count < 2) {
			showUserOptions(terminal);
			return;
		}
		stier.nextToken();
		String cmd = stier.nextToken();
		if ("ls".equalsIgnoreCase(cmd) && count == 2) {
			showAllUser(terminal);
		} else if ("add".equalsIgnoreCase(cmd) && count == 2) {
			addUser(terminal);
		} else if ("del".equalsIgnoreCase(cmd) && count == 3) {
			String delUserID = stier.nextToken();
			deleteUser(terminal, delUserID);
		} else if ("update".equalsIgnoreCase(cmd) && count == 3) {
			String upUserID = stier.nextToken();
			updateUser(terminal, upUserID);
		} else if ("active".equalsIgnoreCase(cmd) && count == 3) {
			String activeUserID = stier.nextToken();
			activeUser(terminal, activeUserID);
		} else if ("changepass".equalsIgnoreCase(cmd) && count == 3) {
			String upPassUserID = stier.nextToken();
			updateUserPass(terminal, upPassUserID);
		} else if ("resetpass".equalsIgnoreCase(cmd) && count == 3) {
			String resetPassUserID = stier.nextToken();
			resetUserPass(terminal, resetPassUserID);
		} else {
			showUserOptions(terminal);
		}
		terminal.println("");
	}

	// 显示操作列表
	public void showUserOptions(Terminal terminal) throws Exception {
		terminal.println(" user ls                         --show all user");
		terminal.println(" user add                        --add new user");
		terminal.println(" user del         <User ID>      --delete user");
		terminal.println(" user update      <User ID>      --update user");
		terminal.println(" user active      <User ID> 	   --change active status of a user");
		terminal.println(" user changepass  <User ID>      --change user password");
		terminal.println(" user resetpass   <User ID>      --reset user password");
		terminal.println("");
	}

	// 显示用户列表
	public void showAllUser(Terminal terminal) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = serviceFactory.lookup("DSB/UserService");
		Collection<UserInfo> result = userService.getAllUsers();
		if (result.size() < 1) {
			terminal.println("0 user(s) was found!");
			return;
		}
		String[] tableHAD = { "User ID", "User Name", "Email", "Locale", "active", "deleted", "Description", "Login ID", "Role ID" };
		String[] tableGAP = { "-------", "---------", "-----", "------", "------", "-------", "-----------", "--------", "-------" };
		int[] format = { 10, 15, 25, 7, 7, 8, 20, 15, 20 };
		terminal.println(CommandHelper.format(tableHAD, format));
		terminal.println(CommandHelper.format(tableGAP, format));
		for (UserInfo user : result) {
			Object[] row = { user.getId(), user.getName(), user.getEmail(), user.getLocale(), user.getActive(), user.getDeleted(), user.getDescription(), user.getLoginId() };
			terminal.println(CommandHelper.format(row, format));
		}
		terminal.println("\nUser List Size : " + result.size());
	}

	// 添加用户
	private void addUser(Terminal terminal) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = (UserService) serviceFactory.lookup("DSB/UserService");
		UserInfo newUser = new UserInfo();
		terminal.print("\nPlease input the new user Name:");
		newUser.setName(terminal.read());
		terminal.print("\nPlease input the new user Description:");
		newUser.setDescription(terminal.read());
		terminal.print("\nPlease input the new user Email:");
		newUser.setEmail(terminal.read());
		boolean flag = true;
		while (flag) {
			terminal.print("\nPlease Input new user Locale (ZN/EN):");
			String tempLocale = terminal.read();
			if ("ZN".equals(tempLocale) || "EN".equals(tempLocale)) {
				newUser.setLocale(tempLocale);
				break;
			} else {
				terminal.println("Invalid input option!");
				continue;
			}
		}
		terminal.print("\nPlease input the new user Login ID:");
		newUser.setLoginId(terminal.read());
		terminal.print("\nPlease input the new user Login Password:");
		newUser.setLoginPass(UserMD5.md5(terminal.read()));
		userService.createUser(newUser);
		terminal.println("\nCreate user successfully!");
		terminal.print("\nShow user list? <Y/N>:");
		if ("Y".equalsIgnoreCase(terminal.read())) {
			showAllUser(terminal);
		}
	}

	// 修改用户
	private void updateUser(Terminal terminal, String upUserID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = (UserService) serviceFactory.lookup("DSB/UserService");
		UserInfo upUser = userService.getUserByID(Long.parseLong(upUserID));
		if (upUser == null) {
			terminal.println("User ID [" + upUserID + "] not found.");
			return;
		}
		if (upUser.getDeleted() == 1) {
			terminal.print("\nPlease input the new user Name:");
			upUser.setName(terminal.read());
			terminal.print("\nPlease input the new user Description:");
			upUser.setDescription(terminal.read());
			terminal.print("\nPlease input the new user Email:");
			upUser.setEmail(terminal.read());
			boolean flag = true;
			while (flag) {
				terminal.print("\nPlease Input new user Locale (ZN/EN):");
				String tempLocale = terminal.read();
				if ("ZN".equals(tempLocale) || "EN".equals(tempLocale)) {
					upUser.setLocale(tempLocale);
					break;
				} else {
					terminal.println("Invalid input option!");
					continue;
				}
			}
			userService.updateUser(Long.parseLong(upUserID), upUser);

			terminal.println("\nUpdate user ID[" + upUserID + "] successfully!");
			terminal.print("\nShow user list? <Y/N>:");
			if ("Y".equalsIgnoreCase(terminal.read())) {
				showAllUser(terminal);
			}
		} else {
			terminal.print("User ID[" + upUserID + "] deleted!\n");
		}
	}

	// 删除用户
	private void deleteUser(Terminal terminal, String delUserID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = (UserService) serviceFactory.lookup("DSB/UserService");
		UserInfo upUser = userService.getUserByID(Long.parseLong(delUserID));
		if (upUser == null) {
			terminal.println("User ID [" + delUserID + "] not found.");
			return;
		}
		terminal.print("Are you sure to delete user with ID [" + delUserID + "] ? (Y/N):");
		if ("Y".equalsIgnoreCase(terminal.read())) {
			userService.deleteUser(Long.parseLong(delUserID));
			terminal.println("\nDelete user ID[" + delUserID + "] sucessfully!\n");
			terminal.print("Show user list? <Y/N>:");
			if ("Y".equalsIgnoreCase(terminal.read())) {
				showAllUser(terminal);
			}
		}
	}

	// 激活用户
	private void activeUser(Terminal terminal, String activeUserID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = (UserService) serviceFactory.lookup("DSB/UserService");
		UserInfo activeUser = userService.getUserByID(Long.parseLong(activeUserID));
		if (activeUser == null) {
			terminal.println("User ID [" + activeUserID + "] not found.");
			return;
		}
		boolean flag = true;
		while (flag) {
			terminal.print("Please input active status (true/false):");
			String tempLocale = terminal.read();
			if ("true".equalsIgnoreCase(tempLocale) || "false".equalsIgnoreCase(tempLocale)) {
				flag = Boolean.parseBoolean(tempLocale);
				break;
			} else {
				terminal.println("Invalid input option!\n");
				continue;
			}
		}
		userService.setUserStatus(Long.parseLong(activeUserID), flag);
		terminal.println("\nChange active status successfully!");
		terminal.print("\nShow user list? <Y/N>:");
		if ("Y".equalsIgnoreCase(terminal.read())) {
			showAllUser(terminal);
		}
	}

	// 修改用户密码
	private void updateUserPass(Terminal terminal, String upPassUserID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = (UserService) serviceFactory.lookup("DSB/UserService");
		UserInfo upPassUser = userService.getUserByID(Long.parseLong(upPassUserID));
		if (upPassUser == null) {
			terminal.println("User ID [" + upPassUserID + "] not found.");
			return;
		}
		terminal.print("Please input the Old Password:");
		String oldPassword = terminal.read();
		terminal.print("\nPlease input the new Password:");
		String newPassword = terminal.read();
		terminal.print("\nPlease confirm the new Password:");
		String confirmPassword = terminal.read();
		if (newPassword != null) {
			if (newPassword.equals(confirmPassword)) {
				if (UserMD5.md5(oldPassword).equals(upPassUser.getLoginPass())) {
					if (!UserMD5.md5(newPassword).equals(upPassUser.getLoginPass())) {
						userService.changePass(Long.parseLong(upPassUserID), UserMD5.md5(oldPassword), UserMD5.md5(newPassword));
					}
					terminal.println("\nChange user [" + upPassUserID + "] password sucessfully!");
					terminal.print("\nShow user list? <Y/N>:");
					if ("Y".equalsIgnoreCase(terminal.read())) {
						showAllUser(terminal);
					}
				} else {
					terminal.println("Wrong input old password!");
				}
			} else {
				terminal.println("Twice input not the same one!");
			}
		}
	}

	// 重置密码
	private void resetUserPass(Terminal terminal, String resetPassUserID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = (UserService) serviceFactory.lookup("DSB/UserService");
		UserInfo resetPassUser = userService.getUserByID(Long.parseLong(resetPassUserID));
		if (resetPassUser == null) {
			terminal.println("User ID [" + resetPassUserID + "] not found.");
			return;
		}
		terminal.print("Are you sure to reset user with ID [" + resetPassUserID + "] password? (Y/N):");
		if ("Y".equalsIgnoreCase(terminal.read())) {
			if (!UserMD5.md5("123456").equals(resetPassUser.getLoginPass())) {
				userService.resetPass(Long.parseLong(resetPassUserID), UserMD5.md5("123456"));
			}
			terminal.println("Reset user with ID [" + resetPassUserID + "] password sucessfully!");
			terminal.print("\nShow user list? <Y/N>:");
			if ("Y".equalsIgnoreCase(terminal.read())) {
				showAllUser(terminal);
			}
		}
	}
}
